package com.feihong.zhiwenlibrary.dialog;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.DialogFragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.feihong.zhiwenlibrary.R;
import com.feihong.zhiwenlibrary.bean.FingerprintIdentify;
import com.feihong.zhiwenlibrary.bean.base.BaseFingerprint;
import com.feihong.zhiwenlibrary.view.DJLMNumPWDKeyboard;
import com.feihong.zhiwenlibrary.view.PasswordEditText;
import com.feihong.zhiwenlibrary.zhiwen.FingerListener;

@SuppressLint("ValidFragment")
public class DJLM_PasswordDialog extends DialogFragment implements PasswordEditText.PasswordFullListener, DJLMNumPWDKeyboard.CustomerKeyboardClickListener,DialogInterface.OnKeyListener {

    private static final String TAG = "指纹";

    public void setCallBack(PasswordDialogListener callBack) {
        this.callBack = callBack;
    }

    private PasswordDialogListener callBack;
    private Dialog mDialog;
    private PasswordEditText editText;
    private DJLMNumPWDKeyboard numPWDKeyboard;
    private View rl_paying;
    private View ll_mmk;
    private View jianpan;
    private View delete_dialog;
    private View view_zhiwen;
    private View iv;
    private ImageView iv_payed;
    private TextView tv_state;
    private View pb_paying;
    private View tv_jiakuan;
    private View tv_torget;
    private TextView tv_yue;
    private View btn_confirm;
    private FingerprintIdentify mFingerprintIdentify;
    private static final int MAX_AVAILABLE_TIMES = 3;

    private TextView txt_title;

    private boolean isEnableFinger = true;
    private String mony = "";
    private boolean failedByDeviceLocked = false;
    private static final int MSG_DEVICELOCK = 10001;
    private static final int STOP_TIME = 30 * 1000;
    private Handler mTimer = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            mTimer.removeMessages(MSG_DEVICELOCK);
            failedByDeviceLocked = false;

        }
    };

    @SuppressLint("ValidFragment")
    public DJLM_PasswordDialog(Context context) {
        super();
        initFinger(context);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


    }

    /**
     * 禁用软键盘的弹出
     *
     * @param view
     */
    private void closeInputMethod(View view) {
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        boolean isOpen = imm.isActive();
        if (isOpen) {
            // imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);//没有显示则显示
            imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        if (mDialog == null) {
            mDialog = new Dialog(getActivity(), R.style.petgirls_dialog);
            mDialog.setContentView(R.layout.password_dialog_keyboardview);
            mDialog.setCanceledOnTouchOutside(false);
            mDialog.getWindow().setGravity(Gravity.BOTTOM);
            Window window = mDialog.getWindow();
            window.setGravity(Gravity.BOTTOM); //可设置dialog的位置
            window.getDecorView().setPadding(0, 0, 0, 0); //消除边距

            WindowManager.LayoutParams lp = window.getAttributes();
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;   //设置宽度充满屏幕
            lp.height = WindowManager.LayoutParams.MATCH_PARENT;
            mDialog.setOnKeyListener(this);
            window.setAttributes(lp);
        }
        View view = mDialog.getWindow().getDecorView();
        editText = (PasswordEditText) view.findViewById(R.id.password_edit_text);
        numPWDKeyboard = (DJLMNumPWDKeyboard) view.findViewById(R.id.custom_key_board);
        rl_paying = view.findViewById(R.id.rl_paying);
        ll_mmk = view.findViewById(R.id.ll_mmk);
        txt_title = (TextView) view.findViewById(R.id.txt_title);
        tv_state = (TextView) view.findViewById(R.id.tv_state);
        tv_yue = (TextView) view.findViewById(R.id.tv_yue);
        iv_payed = (ImageView) view.findViewById(R.id.iv_payed);
        view_zhiwen = view.findViewById(R.id.view_zhiwen);
        jianpan = view.findViewById(R.id.jianpan);
        pb_paying = view.findViewById(R.id.pb_paying);
        tv_jiakuan = view.findViewById(R.id.tv_jiakuan);
        if (tv_jiakuan != null) {
            tv_jiakuan.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (callBack != null) {
                        callBack.onBtnClick(1);
                    }
                }
            });
        }

        tv_torget = view.findViewById(R.id.tv_torget);
        if (tv_torget != null) {
            tv_torget.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (callBack != null) {
                        callBack.onBtnClick(2);
                    }
                }
            });
        }


        delete_dialog = view.findViewById(R.id.delete_dialog);
        iv = view.findViewById(R.id.iv);
        delete_dialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
                callBack.onBtnClick(3);
            }
        });
        btn_confirm = view.findViewById(R.id.btn_confirm);
        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showNumPad();
            }
        });
        view.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showNumPad();
            }
        });
        closeInputMethod(editText);
        init();
        setFinger();
        return mDialog;
    }

    private void initFinger(Context context) {
        try {
            Log.i(TAG, "initFinger: 正在启动......");
            if (mFingerprintIdentify != null) {
                mFingerprintIdentify.cancelIdentify();
            }
            mFingerprintIdentify = new FingerprintIdentify(context, new BaseFingerprint.FingerprintIdentifyExceptionListener() {

                @Override
                public void onCatchException(Throwable exception) {
                    Log.e(TAG, "init: 无法初始化指纹设备，肯能此设备不支持指纹功能...", exception);
                    isEnableFinger = false;
                }
            });                       // 构造对象

            Log.i(TAG, "initFinger: 初始化完毕......" + mFingerprintIdentify);
            // mFingerprintIdentify = new FingerprintIdentify(this, exceptionListener);    // 构造对象，并监听错误回调（错误仅供开发使用）
        } catch (Exception ex) {
            Log.e(TAG, "init: 无法初始化指纹设备，肯能此设备不支持指纹功能...", ex);
            // ex.printStackTrace();
            isEnableFinger = false;
        }
    }

    private void init() {


        editText.setOnPasswordFullListener(this);
        numPWDKeyboard.setOnCustomerKeyboardClickListener(this);
        if (this.mony != null) {
            if (tv_yue != null)
                tv_yue.setText(this.mony);
        }
        showZhiWen();

    }

    private void showZhiWen() {
        if (!isEnableFinger) {
            showNumPad();
            return;
        }
        txt_title.setText("指纹支付");
        if (rl_paying != null) {
            rl_paying.setVisibility(View.GONE);
        }
        if (view_zhiwen != null) {
            view_zhiwen.setVisibility(View.VISIBLE);
        }

        if (jianpan != null) {
            jianpan.setVisibility(View.GONE);
        }
        if (ll_mmk != null) {
            ll_mmk.setVisibility(View.GONE);
        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                kaishishibie();
            }
        }, 200);
    }

    /***
     * 设置余额
     * @param mony
     */
    public void setYue(String mony) {
        if (tv_yue != null) {
            if (mony != null) {
                Log.i(TAG, "setYue: 设置余额" + mony);
                tv_yue.setText(mony);

            }
        }
        this.mony = mony;
    }

    /***
     * 显示数字键盘
     */
    public void showNumPad() {
        try {

            if (mFingerprintIdentify != null) {
                mFingerprintIdentify.cancelIdentify();
            }
        } catch (Exception ex) {
        }
        txt_title.setText("请输入支付密码");
        if (rl_paying != null) {
            rl_paying.setVisibility(View.GONE);
        }
        if (view_zhiwen != null) {
            view_zhiwen.setVisibility(View.GONE);
        }
        if (jianpan != null) {
            jianpan.setVisibility(View.VISIBLE);
        }
        if (ll_mmk != null) {
            ll_mmk.setVisibility(View.VISIBLE);
        }
    }

    /***
     * 设置状态
     * @param resID 图片ID
     * @param info 显示的文字
     */
    public void setState(int resID, String info) {
        if (pb_paying != null) {
            pb_paying.setVisibility(View.GONE);
        }
        if (!TextUtils.isEmpty(info)) {
            tv_state.setVisibility(View.VISIBLE);
            tv_state.setText(info);
        }
        if (resID > 0) {
            iv_payed.setVisibility(View.VISIBLE);
            iv_payed.setImageResource(resID);
        }
    }

    /***
     * 显示等待支付页面
     */
    public void showLoadingView() {
        try {
            if (mFingerprintIdentify != null) {
                mFingerprintIdentify.cancelIdentify();
            }
        } catch (Exception ex) {
        }
        txt_title.setText("正在验证，请稍等");
        if (jianpan != null) {
            jianpan.setVisibility(View.VISIBLE);
        }
        if (ll_mmk != null) {
            ll_mmk.setVisibility(View.GONE);
        }
        if (view_zhiwen != null) {
            view_zhiwen.setVisibility(View.GONE);
        }
        if (rl_paying != null) {
            rl_paying.setVisibility(View.VISIBLE);
        }

    }

    @Override
    public void passwordFull(String password) {
        if (callBack != null) {
            callBack.onDoneInput(this, password);
        }
    }

    @Override
    public void click(String number) {
        editText.addPassword(number);
    }

    @Override
    public void delete() {
        editText.deleteLastPassword();
    }

    @Override
    public void zhiwenzhifu() {

        if (!isEnableFinger) {
            return;
        }
        if (failedByDeviceLocked) {
            Toast.makeText(getActivity(), "指纹验证频率太高,请使用密码支付!", Toast.LENGTH_SHORT).show();
            showNumPad();
            return;
        }
//启动指纹支付
        showZhiWen();


    }


    @Override
    public void onDestroy() {
        try {
            Log.i(TAG, "onDestroy: 正在回收....");
            if (mFingerprintIdentify != null) {
                mFingerprintIdentify.cancelIdentify();
            }
            if (mTimer != null) {
                mTimer.removeMessages(MSG_DEVICELOCK);
                mTimer = null;
            }

        } catch (Exception ex) {
        }
        super.onDestroy();
        callBack = null;

    }

    private FingerListener exceptionListener = new FingerListener() {

        @Override
        public void onCatchException(Throwable exception) {

            Log.e(TAG, "指纹识别 onCatchException: ", exception);
            //ToastUtils.showShort("出错，无法正常使用指纹硬件，请用密码支付!");
            isEnableFinger = false;
            setFinger();
            showNumPad();
        }

        @Override
        public void onSucceed() {
            try {
                if (mFingerprintIdentify != null) {
                    mFingerprintIdentify.cancelIdentify();
                }
            } catch (Exception ex) {
            }
            Log.i(TAG, "指纹识别 onSucceed: ");
            android.widget.Toast.makeText(getActivity(), "验证成功！", android.widget.Toast.LENGTH_SHORT).show();
            if (callBack != null) {
                callBack.successFinger(DJLM_PasswordDialog.this);
            }
            //   dismiss();
        }

        @Override
        public void onNotMatch(int availableTimes) {
            Log.i(TAG, "指纹识别 onNotMatch: " + availableTimes);
            shake(iv);
            btn_confirm.setVisibility(View.VISIBLE);
        }

        @Override
        public void onFailed(boolean isDeviceLocked) {
            Log.i(TAG, "指纹识别 onFailed: " + isDeviceLocked);
            Toast.makeText(getActivity(), "指纹验证失败，请用密码支付！", Toast.LENGTH_SHORT).show();
            isEnableFinger = false;
            showNumPad();
        }

        @Override
        public void onStartFailedByDeviceLocked() {
            Log.i(TAG, "指纹识别 onStartFailedByDeviceLocked: ");
            // ToastUtils.showShort("验证指纹频率高，无法使用指纹功能，请用密码支付!");
            isEnableFinger = false;
            failedByDeviceLocked = true;
            //mTimer.sendEmptyMessageDelayed(MSG_DEVICELOCK, STOP_TIME);
            Toast.makeText(getActivity(), "指纹验证失败频率太高,请使用密码支付!", Toast.LENGTH_SHORT).show();
            showNumPad();
        }
    };


    /***
     * 判断是否支持指纹功能
     * @return
     */
    public boolean isFingerprintEnable() {
        try {
            if (mFingerprintIdentify == null) {
                Log.e(TAG, "指纹对象NULL,请先调用show方法，然后再调用isFingerprintEnable", new Exception("指纹对象NULL,请先调用show方法，然后再调用isFingerprintEnable"));
                return false;
            }
            return mFingerprintIdentify.isFingerprintEnable();

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;

    }

    private void kaishishibie() {
        try {
            try {
                if (mFingerprintIdentify != null) {
                    mFingerprintIdentify.cancelIdentify();
                }
            } catch (Exception ex) {
            }
            if (mFingerprintIdentify == null) {
                Log.i(TAG, "kaishishibie: 无法初始化....mFingerprintIdentify = null");
                //   ToastUtils.showShort("此设备不支持指纹功能，请用密码支付！");
                isEnableFinger = false;
                showNumPad();
                return;
            }
            if (!mFingerprintIdentify.isFingerprintEnable()) {
                Log.i(TAG, "zhiwen: 是否支持指纹:" + mFingerprintIdentify.isFingerprintEnable());
                //ToastUtils.showShort("此设备不支持指纹功能【请检查是否开启指纹功能】，请用密码支付！");
                isEnableFinger = false;
                showNumPad();
                return;
            }
            //  mFingerprintIdentify.isFingerprintEnable();                                 // 指纹硬件可用并已经录入指纹
            boolean isHardwareEnable = mFingerprintIdentify.isHardwareEnable();// 指纹硬件是否可用
            Log.i(TAG, "zhiwen: 指纹硬件是否可用:" + isHardwareEnable);
            if (!isHardwareEnable) {
                //   ToastUtils.showShort("无法注册指纹硬件，请用密码支付！");
                isEnableFinger = false;
                showNumPad();
                return;
            }

            boolean isRegisteredFingerprint = mFingerprintIdentify.isRegisteredFingerprint();
            Log.i(TAG, "zhiwen: 注册指纹硬件:" + isRegisteredFingerprint);
            if (!isRegisteredFingerprint) {
                //ToastUtils.showShort("手机没有开启指纹功能，请用密码支付！");
                isEnableFinger = false;
                showNumPad();
                return;
            }
            mFingerprintIdentify.startIdentify(3, exceptionListener);
        } catch (Exception ex) {
            //   ToastUtils.showShort("出错，请用密码支付！");
            Log.e(TAG, "指纹: ", ex);
            //dismiss();
            isEnableFinger = false;
            showNumPad();
        }
    }


    private void shake(View v) {
        Animation shake = AnimationUtils.loadAnimation(getActivity(), R.anim.password_dialog_shake);
        v.startAnimation(shake);
    }

    /***
     * 启用指纹支付功能 ，默认true ,true 启用  false 关闭  ，关闭键盘上不显示
     * @param enableFinger
     */
    public void setEnableFinger(boolean enableFinger) {

        isEnableFinger = enableFinger;
        Log.i(TAG, "setFinger: 开启关闭指纹:" + isEnableFinger);
        setFinger();
    }

    private void setFinger() {
        if (numPWDKeyboard == null) {
            return;
        }
        //
        //   numPWDKeyboard.setEnableFinger(isEnableFinger);
    }

    @Override
    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            if(callBack != null){
                callBack.onBtnClick(3);
            }
            return true;
        }
        return false;
    }
}
